import uvicorn
from fastapi import FastAPI, Request
from datacache import get_sz_stocks, get_stock_day_data
from datacache import get_stock_data
from datetime import datetime
from combinations import get_filtered_stock, calc_index_stock_corr

app = FastAPI()

@app.get("/get-stocks")
def get_sz_stocks_data(request: Request):
    plate = request.query_params.get("plate")
    df = get_sz_stocks(plate)
    return df.to_dict('records')

@app.get("/get-stock-kline")
def get_sz_stock_kline_data(request: Request):
    code = request.query_params.get("code")
    start_date = '20200101'
    end_date_base = datetime.now().strftime('%Y%m%d')
    df = get_stock_data(code, start_date, end_date_base)
    return df.fillna(0).to_dict('records')

@app.get("/get-stock-time-data")
def get_sz_stock_time_data(request: Request):
    # 获取某个股票某个日期的分时数据
    code = request.query_params.get("code")
    date = request.query_params.get("date").replace("-", "")
    df = get_stock_day_data(code, date)
    return df.to_dict('records')

@app.get("/get-filtered-stock")
def get_filtered_stock_get(request: Request):
    runtime = request.query_params.get("runtime") == 'true' # 获取实时行情
    df = get_filtered_stock(runtime)
    return df.fillna(0).to_dict('records')

@app.get("/calc-stock-index-corr")
def calc_stock_index_corr(request: Request):
    index_code = request.query_params.get("indexCode")
    stock_code = request.query_params.get("stockCode")
    return calc_index_stock_corr(stock_code=stock_code, index_code=index_code)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    uvicorn.run(
        app="main:app",
        host="127.0.0.1",
        port=8848,
        reload=False
    )
